package top.riske.animalhazardassessment.analyse.controller;

import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import top.riske.animalhazardassessment.ai.DataReceivedCallback;
import top.riske.animalhazardassessment.ai.DeepSeekService;

import java.io.IOException;

@ServerEndpoint("/analyse/image")
@Component
public class AnalyseWebsocket {

    private Session session;

    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("连接成功");
        this.session = session;

        session.getBasicRemote().sendText("已连接上");
    }

    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public String onMsg(String text) throws IOException {
        System.out.println("servet 接收到：" + text);
        if(text.startsWith("scan:")){
            text  = text.substring(5);
            if(text.startsWith("http")){
                session.getBasicRemote().sendText("已经收到图片链接，即将开始识别："+text);
                session.getBasicRemote().sendText("start");

                scanImage(text);
                return "over";
            }else{
                return "无效的图片链接："+text;
            }
        }
        return "收到消息：" + text;
    }

    void scanImage(String imageUrl) throws IOException {
        try {
            DeepSeekService.scanImageForAnimal(imageUrl, new DataReceivedCallback() {
                @Override
                public void onDataReceived(String newData) throws IOException {
                    session.getBasicRemote().sendText(newData);
                }

                @Override
                public void onProcessCompleted(String fullContent) throws IOException {
                    session.getBasicRemote().sendText("over");
                }

                @Override
                public void onError(Exception error) throws IOException {
                    session.getBasicRemote().sendText("出错啦，请稍后再试："+error.getMessage());

                }
            });
        } catch (NoApiKeyException e) {
            session.getBasicRemote().sendText("阿里云API密钥无效");
        } catch (UploadFileException e) {
            session.getBasicRemote().sendText("图片上传错误，请重试");

        }
    }

}